import 'package:df/page/assets/assets_key.dart';
import 'package:df/page/login/lark/lark_login.dart';
import 'package:df/page/login/login.dart';
import 'package:df/page/login/login_response.dart';
import 'package:df/page/login/wechat/wechat_login.dart';
import 'package:df/page/splash/splash_page.dart';
import 'package:df/page/web/language_locale.dart';
import 'package:df/utils/icon_icon_data.dart';
import 'package:df/utils/sp_key.dart';
import 'package:df/utils/sp_utils.dart';
import 'package:df/widgets/dialog_loading.dart';
import 'package:df/page/router/router.dart';
import 'package:df/utils/logger_utils.dart';
import 'package:df/widgets/MessageDialog.dart';
import 'package:df/widgets/toast_utils.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:lark_auth/lark_auth.dart';
import 'package:provider/provider.dart';
import 'package:df/service/api_service.dart';
import 'package:df/page/login/view_model/login_view_model.dart';
import 'package:df/generated/l10n.dart';
import 'package:flutter/foundation.dart';
import 'package:url_launcher/url_launcher.dart';

late LoadingDialog _loadingDialog;
class LoginPage extends StatefulWidget {

  final String title;
  const LoginPage({Key? key, required this.title}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();

  static void doLogin(Login login, BuildContext context) {
    _loadingDialog = new LoadingDialog( //调用对话框
      text: S.of(context).pleaseWait,
    );
    showDialog<Null>(
        context: context, //BuildContext对象
        barrierDismissible: false,
        builder: (BuildContext context) {
          return _loadingDialog;
        });

    Future<LoginResponse> loginResponse = ApiService.postLogin(login);
    loginResponse.then((response) {
      LogUtils.w("【登录】结果= ${response.resultMsg}");
      int? code = response.resultCode;
      LogUtils.w("【登录】结果= ${code}");
      if(code == ApiService.kCodeSuccess) {
        String? wxUnionId = response.data?.user?.wxUnionId;
        String? larkUnionId = response.data?.user?.flyUnionId;
        String? userId = response.data?.user?.userId;
        LogUtils.w("【登录成功】微信Id= ${wxUnionId}");
        LogUtils.w("【登录成功】飞书Id= ${larkUnionId}");
        final Map<String, String?> newQueries = <String, String?> {
          SpKey.kSpWechatUnionId: wxUnionId,
          SpKey.kSpLarkUnionId: larkUnionId,
          SpKey.kSpUserId: userId,
        };
        GoRouter.of(context).pushNamed(ROUTER_WEB, queryParameters: newQueries);
        RouterId.saveId(wxUnionId, larkUnionId, userId);
      } else {
        ToastUtils.show('${S.current.loginFailed}:\n${response.resultMsg}');
      }

      _loadingDialog.pop();
    });
  }
}


class _LoginPageState extends State<LoginPage> {
  TextEditingController _usernameController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();

  final RegExp emailReg = RegExp(r"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?");
  final GlobalKey _formKey = GlobalKey<FormState>();
  late String _accountOrEmail;
  late String _password;
  bool _isObscure = true;
  Color _eyeColor = Colors.grey;


  @override
  void initState() {
    // 获取接口数据
    //JokeService.getJokes(Provider.of<JokeViewModel>(context, listen: false));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        top: true,
        bottom: false,
        left: false,
        right: false,

        child: Consumer<LoginViewModel>(
          builder: (context, loginViewModel, child) {
            LoginViewModel _loginViewModel = loginViewModel;

            return Padding(
              padding: EdgeInsets.fromLTRB(10, 10, 10, 10),

              child: Scaffold(
                body: Form(
                  key: _formKey, // 设置globalKey，用于后面获取FormStat
                  autovalidateMode: AutovalidateMode.onUserInteraction,
                  child: ListView(
                    padding: const EdgeInsets.symmetric(horizontal: 20),
                    children: [
                      const SizedBox(height: 60),
                      buildAccountOrEmail(context), // 输入邮箱
                      const SizedBox(height: 30),
                      buildPasswordTextField(context), // 输入密码

                      // buildForgetPasswordText(context), // 忘记密码

                      const SizedBox(height: 60),
                      buildLoginButton(context), // 登录按钮
                      const SizedBox(height: 40),
                      if (Splash.vShowOtherLogin) buildOtherLoginText(context) else const SizedBox(), // 其他账号登录
                      if (Splash.vShowOtherLogin) buildOtherMethod() else const SizedBox(), // 其他登录方式
                      if (!Splash.vShowOtherLogin) buildRegisterText(context) else const SizedBox(), // 注册
                      //TODO 跳转AppStore、App名称多语言
                    ],
                  ),
                ),
              ),
              //https://blog.csdn.net/weixin_43734095/article/details/124335584,
            );
          },
        ),
      ),
    );
  }


  Widget buildRegisterText(context) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.only(top: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            GestureDetector(
              child: Text(S.of(context).noAccount, style: TextStyle(fontSize: 18),),
              onLongPress: () {
                LogUtils.d("【点击】注册");
                if(true) {
                  GoRouter.of(context).pushNamed(ROUTER_CAMERA);
                } else {
                  _launchAppStore();
                }
              },
            ),

            GestureDetector(
              child: Text(S.of(context).clickRegister, style: TextStyle(color: Colors.cyan, fontSize: 18)),
              onTap: () {
                LogUtils.d("【点击】注册");
                GoRouter.of(context).pushNamed(ROUTER_REGISTER);
              },
            )

          ],
        ),
      ),
    );
  }

  Future<void> _launchAppStore() async {
    const url = 'https://apps.apple.com/app/id1614180416';
    Uri uri = Uri.parse(url);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    } else {
      ToastUtils.show(S.current.notSupportingRedirection);
    }
  }

  Widget buildOtherMethod() {
    const IconData lark = IconIconData(0xfA001);

    return ButtonBar(
      alignment: MainAxisAlignment.center,
      children: [
        IconButton(
            icon: Image.asset(
              AssetsKey.kIconLark,
              width: 34, // 图片宽度
              height: 34, // 图片高度
            ),
            // icon: Icon(Icons.facebook, color: Theme.of(context).iconTheme.color),

            onPressed: () {
              callback(Lark response) {
                int errCode = response.code;
                String msg = response.msg;
                String? larkUnionId = response.data;
                LogUtils.w("【飞书登录】数据= ${larkUnionId}；响应码= ${errCode}；信息= ${msg}");
                if(errCode == kCodeSuccess) {
                  LogUtils.w('【登录】飞书Id= $larkUnionId');
                  Login login = Login(
                    loginType: ELoginType.FhChat.value,
                    flyUnionid: larkUnionId,
                  );
                  LoginPage.doLogin(login, context);
                }
              }
              Future<LarkAuth?> larkAuth = larkLogin("zh", callback);
              LogUtils.w("【飞书登录】数据= ${larkAuth}");
            }),
        IconButton(
            icon: Icon(Icons.wechat, color: Theme.of(context).iconTheme.color),
            onPressed: () {
              callback(WeChat response) {
                int errCode = response.code;
                String msg = response.msg;
                String? wxUnionId = response.data;
                LogUtils.w("【微信登录】数据= ${wxUnionId}；响应码= ${errCode}；信息= ${msg}");
                if(errCode == kCodeSuccess) {
                  LogUtils.w('【登录】微信Id= $wxUnionId');
                  Login login = Login(
                    loginType: ELoginType.WxChat.value,
                    wxUnionId: wxUnionId,
                  );
                  LoginPage.doLogin(login, context);
                } else {
                  ToastUtils.show("${S.current.weChatLoginError}\n${msg}");
                }
              }
              wechatLogin(callback);
            }),
        GestureDetector(
          child: IconButton(icon: Icon(Icons.qr_code, color: Theme.of(context).iconTheme.color),
            // child: IconButton(icon: Icon(Icons.qr_code_scanner, color: Theme.of(context).iconTheme.color),
            onPressed: () {
              GoRouter.of(context).pushNamed(ROUTER_SCAN);
              LogUtils.w("【扫码登录】扫码：微信、飞书");
            },
          ),
          onLongPress: () {
            GoRouter.of(context).pushNamed(ROUTER_CAMERA);
          },
        ),
        GestureDetector(
          child: IconButton(icon: Icon(Icons.phone_iphone, color: Theme.of(context).iconTheme.color),
            onPressed: () {
              GoRouter.of(context).pushNamed(ROUTER_SMS);
            },
          ),
          onLongPress: () {
            GoRouter.of(context).pushNamed(ROUTER_CAMERA);
          },
        ),

      ],

    );
  }
  Widget buildOtherLoginText(BuildContext context) {
    return Center(
      child: Text(
        S.of(context).loginAnotherAccount,
        style: TextStyle(color: Colors.grey, fontSize: 14),
      ),
    );
  }

  Widget buildPasswordTextField(BuildContext context) {
    return TextFormField(
        controller: _passwordController,
        obscureText: _isObscure, // 是否显示文字
        onSaved: (v) => _password = v!,
        validator: (v) {
          if (v!.isEmpty) {
            return S.of(context).pleaseEnterPassword;
          }
        },
        decoration: InputDecoration(
            labelText: S.of(context).password,
            suffixIcon: IconButton(
              icon: Icon(
                Icons.remove_red_eye,
                color: _eyeColor,
              ),
              onPressed: () {
                // 修改 state 内部变量, 且需要界面内容更新, 需要使用 setState()
                setState(() {
                  _isObscure = !_isObscure;
                  _eyeColor = (_isObscure
                      ? Colors.grey
                      : Theme.of(context).iconTheme.color)!;
                });
              },
            )));
  }



  Widget buildAccountOrEmail(BuildContext context) {
    return TextFormField(
      controller: _usernameController,
      decoration: InputDecoration(labelText: S.of(context).loginName),
      validator: (v) {
        if (v!.isEmpty) {
          return S.of(context).pleaseEnterAccount;
        }
      },

      onSaved: (v) {
        _accountOrEmail = v!;
      },
    );
  }

  Widget buildLoginButton(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        if ((_formKey.currentState as FormState).validate()) {
          (_formKey.currentState as FormState).save();
          Login login;
          if (emailReg.hasMatch(_accountOrEmail)) {
            LogUtils.w('【登录】邮箱= $_accountOrEmail, 密码= $_password');
            login = Login(
              loginType: ELoginType.Email.value,
              emailAddress: _accountOrEmail,
              pwd: _password,
            );
          } else {
            LogUtils.w('【登录】账号= $_accountOrEmail, 密码= $_password');
            login = Login(
              loginType: ELoginType.Account.value,
              account: _accountOrEmail,
              pwd: _password,
            );
          }

          LoginPage.doLogin(login, context);
        } else {
          ToastUtils.show(S.current.invalidInput);
          LogUtils.e("【登录成功】请正确输入，账号= ${(_accountOrEmail ?? '')}；密码= ${_password ?? ''}");
        }
      },

      child: Text(
        S.of(context).login,
        style: TextStyle(
          fontSize: 20.0,
          //fontWeight: FontWeight.bold,
          //color: Colors.grey[500]!, // 设置文本颜色
        ),
      ),
    );

  }


  bool _isButtonEnabled() {
    return _usernameController.text.isNotEmpty &&
        _passwordController.text.isNotEmpty;
  }

}
